<template>
  <div class="node-config-calculator">
    <div>
      <label>
        输入变量
      </label>
      <!-- 添加输出变量 -->
      <el-icon @click.prevent="addScriptInputParam"
               class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer">
        <CirclePlus/>
      </el-icon>
    </div>
    <div class="user-script-param-list">
      <div
          class="user-script-param-item"
          v-for="(item,index) in Calculator.InputParams"
          :key="index">
        <el-input placeholder="输入变量名称" clearable
                  v-model="item.TargetParamName"
                  size="small" style="margin-right: 10px;width: 160px"
        >
        </el-input>
        <el-select
            clearable
            v-model="item.ValueType"
            placeholder="请选择类型"
            size="small"
            style="width: 110px; margin-right: 10px;"
        >
          <el-option
              v-for="item in ValueTypes"
              :key="item"
              :label="item"
              :value="item"
          >
          </el-option>
        </el-select>
        <!--        <data-source-input-->
        <!--            :datasource-item="item" :node-id="item.DataSourceId" :param-name="item.ParamName"-->
        <!--            null-message="请选择数据来源（不能为空）"-->
        <!--            @change="onChange($event,index)"/>-->
        <el-input
            v-model="item.ParamName"
            style="width: 340px"
            placeholder="输入计算公式"
            size="small"
        >
          <template #prefix>
            <el-icon class="el-input__icon" style="cursor: pointer" @click="EditCalculatorBtn(index,item.ParamName)">
              <CalculatorIcon/>
            </el-icon>
          </template>
        </el-input>
        <el-button
            icon="Delete" style="color: red" type="text" size="small"
            circle @click.prevent="deleteScriptInputParam(index)"
        ></el-button>
        <!--        <n-icon size="14" :component="CalculatorIcon" />-->
      </div>
      <el-form-item label="描述" style="margin-top: 10px">
        <el-input
            v-model="Calculator.Desc"
            type="textarea"
            :rows="6"
            placeholder="请输入描述"
            style="width: 90%"
        ></el-input>
      </el-form-item>
    </div>

    <el-dialog
        v-model="ShowEditCalculatorDialog"
        class="edit-calculator" style="padding: 0"
        header-class="edit-calculator-header"
        body-class="edit-calculator-body"
        title="编辑公式" width="500" draggable overflow
    >
      <div>
        <!-- 遮罩层，点击遮罩层隐藏计算器 -->
        <div class="mask" @click="$emit('hideCalc')"></div>
        <div :style="{ top: top + 'px', left: left + 'px' }" class="calculator">
          <div class="showPanel">
            <el-input v-model.value="ExpressionContext"
                      style="font-size: 15px;font-weight: 600;"
                      :autosize="{ minRows: 5, maxRows: 5 }"
                      ref="inputRef" id="ExpressionId" type="textarea"/>
            <!--            <el-input v-model.value="exp"/>-->
            <!--            <span class="number">{{ number }}</span>-->
          </div>
          <div class="caculator-button">
            <el-button @click="getResult('C')">C</el-button>
            <el-button @click="getResult('/')">/</el-button>
            <el-button @click="getResult('*')">*</el-button>
            <el-button @click="getResult('del')" icon="delete" type="danger"></el-button>

            <el-button @click="getResult('7')">7</el-button>
            <el-button @click="getResult('8')">8</el-button>
            <el-button @click="getResult('9')">9</el-button>
            <el-button @click="getResult('-')">-</el-button>

            <el-button @click="getResult('4')">4</el-button>
            <el-button @click="getResult('5')">5</el-button>
            <el-button @click="getResult('6')">6</el-button>
            <el-button @click="getResult('+')">+</el-button>

            <el-button @click="getResult('1')">1</el-button>
            <el-button @click="getResult('2')">2</el-button>
            <el-button @click="getResult('3')">3</el-button>
            <!--            <el-button @click="getResult('=')" type="primary">=</el-button>-->

            <el-button @click="getResult('%')">%</el-button>
            <el-button @click="getResult('0')">0</el-button>
            <el-button @click="getResult('.')">.</el-button>
            <el-button @click="getResult('')" icon="Link"></el-button>
          </div>
          <div class="caculator-button">
            <!--            :datasource-item="item" :node-id="item.DataSourceId" :param-name="item.ParamName"-->
            <!--            @change="onChange($event,index)"-->
            <data-source-input null-message="请选择数据来源（不能为空）" @change="onChange"
                               style="width: 220px"/>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CloseEditCalculatorDialog">取消</el-button>
          <el-button type="primary" @click="ConfirmEditCalculatorDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import Utils from '../../../../utils/Common'
import FlowNodeDataApi from '@/api/flow/FlowNodeDataApi'
import { useFlowStore } from "@/store/modules/flow/flowStore";
import { nextTick, onMounted, ref } from "vue";
import DataSourceInput from '@/vue2-flow/src/views/flow/components/NodeInputSourceDataComponent.vue'
import { AppParams } from '@/utils/appParams'
import { icon } from "@/plugins";

const CalculatorIcon = icon.ionicons5.CalculatorIcon
const FlowStore = useFlowStore()

const Calculator = ref({
  InputParams: [
    { TargetParamName: 'Input0', DataSourceId: '0', DataSource: 'NULL', ParamName: '', Value: '', ValueType: '' }
  ],
  Desc: null
})

const ValueTypes = ref(AppParams.COMMON.DATA_TYPE)
const ShowEditCalculatorDialog = ref(false)
const CurrentEditIndex = ref(-1);
const rewrite = ref(false);
const ExpressionContext = ref('');
let exp = ref('');

/**
 *
 * @param item
 * @param itemIndex
 */
const onChange = (item, itemIndex) => {
  if (!Utils.IsEmpty(item)) {
    const pdd = [item.DataSource, item.nodeId, item.ParamName].join('_')
    AppendValue(' ${' + pdd + '} ', 'add')
  }
}
const inputRef = ref(null);

/**
 * 删除输入变量
 * @param index
 */
const deleteScriptInputParam = (index) => {
  Calculator.value.InputParams.splice(index, 1)
}

const CloseEditCalculatorDialog = () => {
  ShowEditCalculatorDialog.value = false
}

const ConfirmEditCalculatorDialog = () => {
  CloseEditCalculatorDialog()
  // let cp = Calculator.value.InputParams[CurrentEditIndex.value];

  Calculator.value.InputParams[CurrentEditIndex.value].ParamName = ExpressionContext.value
  ExpressionContext.value = '';
  //
  // Calculator.value.InputParams[itemIndex].ParamName = item.ParamName
  // Calculator.value.InputParams[itemIndex].DataSource = item.DataSource
  // Calculator.value.InputParams[itemIndex].DataSourceId = item.nodeId
}

const getResult = (key) => {
  switch (key) {
    case 'C':
      ExpressionContext.value = '';
      break;
    case 'del':
      AppendValue('', 'sub')
      break;
    default:
      AppendValue(key, 'add')
      break;
  }
}

const AppendValue = (key, option) => {
  let _Element = document.getElementById('ExpressionId');
  if (_Element) {
    let selectionStartIndex = _Element.selectionStart
    let selectionEndIndex = _Element.selectionEnd

    if (option === 'sub') {
      --selectionStartIndex;
    }
    let before = ExpressionContext.value.slice(0, selectionStartIndex);
    let after = ExpressionContext.value.slice(selectionEndIndex);
    ExpressionContext.value = before + key + after;
    // 将光标移动到插入文本之后
    _Element.setSelectionRange(before + key.length - 1, before + key.length);
    _Element.focus();
  }
}

const addScriptInputParam = () => {
  const Count = Calculator.value.InputParams.length
  Calculator.value.InputParams.push({
    TargetParamName: 'Input' + Count,
    DataSource: 'NULL',
    DataSourceId: '0',
    ParamName: '',
    Value: '',
    ValueType: ''
  })
}

/**
 * 编辑公式按钮
 * @param index
 * @constructor
 */
const EditCalculatorBtn = (index, exp) => {
  ExpressionContext.value = exp;
  CurrentEditIndex.value = index;
  ShowEditCalculatorDialog.value = true
}

/**
 * 设置回显的表单数据
 * @param _node
 * @constructor
 */
const SetFormValue = (_node) => {
  const _Calculator = _node?.nodeInputParam?.NodeLogic?.Calculator || {
    InputParams: [{
      TargetParamName: 'Input0',
      DataSource: 'NULL',
      DataSourceId: '0',
      ParamName: '',
      Value: '',
      ValueType: ''
    }],
    Desc: ''
  }
  console.warn(_Calculator)
  if (_Calculator) {
    Calculator.value = _Calculator
    Calculator.value.Desc = _node?.nodeInputParam?.Desc
  }
}

/**
 * 保存节点输入参数
 * @param NodeName
 * @private
 */
const _SaveNode = (NodeName) => {
  const NodeInputParam = Calculator.value
  const params = {
    NodeLogic: {
      Calculator: {
        InputParams: NodeInputParam.InputParams
      }
    },
    Desc: NodeInputParam.Desc
  }
  new FlowNodeDataApi().Install(FlowStore.CurrentClickNode.id, params, NodeName)
}
const ShowNodeData = () => {
  SetFormValue(FlowStore.CurrentClickNode)
}
onMounted(() => {
  ShowNodeData()
})

defineExpose({
  _SaveNode
})

</script>

<style lang="scss">
.edit-calculator {
  padding: 0;

  #ExpressionId {
    font-size: 15px;
    font-weight: 900;
  }

  .edit-calculator-header {
    display: flex;
    align-items: center;
    height: 38px;
    padding-left: 10px;

    span {
      font-weight: 600;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-bottom: 10px;
    padding-right: 10px;

    button {
      width: 100px;
      margin-left: 10px;
    }
  }

  .el-dialog__header {
    background-color: unset;

    span {
      color: #606266;;
    }
  }

  .edit-calculator-body {
    height: 370px;

    > div {
      display: flex;
      justify-content: center;
    }
  }
}
</style>
<style lang="less" scoped>
.node_script_compile {
  p {
    white-space: pre-line;
  }
}

.node-config-calculator {
  width: 100%;
  min-width: 600px;
  height: calc(100vh - 110px);
  overflow-x: auto;

  flex: 1;
  display: flex;
  flex-direction: column;


  .mask {
    position: absolute;
    //z-index: 80;
    top: 0;
    left: 0;
    //width: 100vw;
    //height: 100vh;
  }

  .calculator {
    //position: fixed;
    //z-index: 99;
    border: solid 1px #dcdfe6;
    padding: 5px;
    background-color: #fffffff1;
    border-radius: 4px;
    box-shadow: 0 0 2px #dcdfe6;
    width: 95%;
    display: flex;
    flex-direction: column;

    .showPanel {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      //padding: 2px 20px;
      height: 130px;
      //border: 1px #f0f0f0 solid;
      width: 100%;
      border-radius: 4px;
      box-sizing: border-box;
      margin-bottom: 3px;
      justify-content: space-evenly;

      .el-textarea {
        //height: 40px;
        .el-textarea__inner {
          font-size: 15px;
          font-weight: 900;
        }

        textarea {
          font-size: 15px;
          font-weight: 900;
        }
      }

      .exp {
        color: #aaa;
        font-size: 10px;
        height: 12px;
      }

      .number {
        font-size: 16px;
        font-weight: 900;
      }

      .el-input__wrapper {
        box-shadow: unset;
      }
    }

    // 删除的icon图标
    ::v-deep.delete {
      display: inline-block;
      width: 20px;
      height: 12px;
      background: url('../../icon/calcDetele.png') no-repeat center center;
      background-size: 90% 90%;
    }
  }


  .caculator-button {
    margin: 0 auto;
    width: 220px;
    display: grid;
    border: solid 1px #eee;
    padding: 6px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    gap: 3px;
    border-radius: 4px;
    background-color: #fffffff1;

    .el-button {
      margin: 0;
      padding: 10px;
      font-weight: 600;
      // width: 100%;
    }
  }

  #result {
    margin-bottom: 6px;
  }

  .equal {
    grid-column: 4/5;
    grid-row: 4/6;
  }

  .user-script-param-list {
    overflow-y: auto;

    .user-script-param-item {
      display: flex;
      padding-top: 10px;
    }
  }

  .user-script-space {
    flex: 1;
    padding: 10px 0;

    .user-script-edit {
      .go-editor-area {
        .monaco-editor {
          background-color: rgb(0 0 0 / 84%) !important;
        }
      }

    }
  }

  .user-script-desc {
    width: 300px;
    padding-left: 10px;
  }

  .el-dialog__body {
    padding-top: 20px;
    height: calc(100% - 100px);
  }

  .el-dialog__header {
    background-color: #545c64;
    padding: 20px 10px;

    .el-dialog__title {
      color: #ffffff;
    }
  }
}
</style>
